import uiautomator2 as u2
import requests
import subprocess

class DevicesDriver():

    def __init__(self):
        self.devices_number_list = self.get_device_number_list()
        self.devices_list = self.get_all_device(self.devices_number_list)

    def start_uiautomator_server(self, devices_obj):
        try:
            port = devices_obj['port']
            start_server = f"http://127.0.0.1:{port}/services/uiautomator"
            response = requests.post(start_server)
            data = response.json()
            if data['success'] == True:
                devices_obj['status'] = "success"
        except Exception:
            pass
        finally:
            return devices_obj


    def get_device_number_list(self):
        """获取手机设备"""
        cmd = r'adb devices'  # % apk_file
        pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
        pr.wait()  # 不会马上返回输出的命令，需要等待
        out = pr.stdout.readlines()  # out = pr.stdout.read().decode("UTF-8")
        devices = []
        for i in (out)[1:-1]:
            device = str(i).split("\\")[0].split("'")[-1]
            devices.append(device)
        return devices  # 手机设备列表

    def get_all_device(self, device_number_list):
        """将所有设备都初始化好，然后加到设备列表中"""
        device_list = []
        for device_number in device_number_list:
            # device_obj = {"device_number": device_number, "device": None, "port": "", "status": "failed"}
            # {'udid': 'Z5Z9NVGUQOQSGM4H-d4:bb:c8:7e:5a:37-V1813A', 'version': '8.1.0', 'serial': 'Z5Z9NVGUQOQSGM4H', 'brand': 'vivo', 'model': 'V1813A', 'hwaddr': 'd4:bb:c8:7e:5a:37', 'sdk': 27, 'agentVersion': '0.10.0', 'display': {'width': 1080, 'height': 2280}, 'battery': {'acPowered': False, 'usbPowered': True, 'wirelessPowered': False, 'status': 5, 'health': 2, 'present': True, 'level': 100, 'scale': 100, 'voltage': 4396, 'temperature': 300, 'technology': 'Li-ion'}, 'memory': {'total': 3805784, 'around': '4 GB'}, 'cpu': {'cores': 8, 'hardware': 'MT6771V/C'}, 'arch': '', 'owner': None, 'presenceChangedAt': '0001-01-01T00:00:00Z', 'usingBeganAt': '0001-01-01T00:00:00Z', 'product': None, 'provider': None}
            try:
                d = u2.connect(device_number)
                d.set_fastinput_ime(True)
                device_obj = d.device_info
                prot = d.uiautomator.service_url.replace("http://", "").split(":")[1].split("/")[0]
                device_obj["device"] = d
                device_obj["port"] = prot
                device_obj = self.start_uiautomator_server(device_obj)
                device_list.append(device_obj)
            except Exception as e:
                print(e)
                continue
        if len(device_list) < 1:
            raise Exception("当前没有检测到任何设备，请检查设备是否已经链接好")
        return device_list


if __name__ == '__main__':
    drv = DevicesDriver()